package org.beian.fmmall.service.TimerJob;

import com.github.wxpay.sdk.WXPay;
import org.beian.fmmall.beans.Orders;
import org.beian.fmmall.dao.OrdersMapper;
import org.beian.fmmall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeOutCheckJob {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderService orderService;


    private WXPay wxPay=new WXPay(new MyPayConfig());
    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAndCloseOrder(){
        //查询可能未支付的订单
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        Date date = new Date(System.currentTimeMillis()-30*60*1000);
        criteria.andEqualTo("status","1");
        criteria.andLessThan("createTime",date);
        List<Orders> orders = ordersMapper.selectByExample(example);
        try {
            //访问微信平台确认当前订单最终的支付状态
            for (int i = 0; i < orders.size(); i++) {
                Orders order = orders.get(i);
                HashMap<String,String> map=new HashMap<>();
                map.put("out_trade_no",order.getOrderId());
                Map<String, String> resp = wxPay.orderQuery(map);
                 if("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))){
                    //订单已经支付，要修改订单的状态为“待发货\已支付”
                    orderService.updateOrderStatus(order.getOrderId(),"2");
                }else if("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))){
                    //确实未支付，则取消订单
                    //a.向微信平台发送请求，关闭当前订单的支付链接
                    Map<String, String> closeResp = wxPay.closeOrder(map);

                    //b.修改当前订单为已关闭和关闭原因为超时
                    orderService.closeOrder(order.getOrderId());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
